import 'package:aihu_getx_app/app/modules/chat/models/user_view_export_req_vo.dart';
import 'package:aihu_getx_app/app/modules/chat/models/user_view_resp_vo.dart';
import 'package:aihu_getx_app/app/modules/chat/providers/chat_provider.dart';
import 'package:aihu_getx_app/app/modules/chat/utils/chat_constants.dart';
import 'package:aihu_getx_app/app/modules/commons/commons.dart';
import 'package:aihu_getx_app/providers/web_socket_manager.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class WsChatController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final String title = "消息中心";
  final String appName = "";

  final count = 0.obs;
  WebSocketManager? _webSocketManager;
  final msgList = <String>[].obs;
  final userViewScrollController = ScrollController();
  final userViewList = <UserViewRespVO>[].obs;
  final loading = false.obs;
  late TabController tabController;
  final _typeList = UserViewListType.values;
  final tabList = <Tab>[].obs;
  final tabIndex = 0.obs;
  final searchForm = UserViewExportReqVO().obs;
  final loadMoreText = "已经到底了~".obs;

  Future onRefresh() {
    if (loading.isTrue) {
      return Future.value();
    }
    onLoading();
    return Future.value();
  }

  void onLoading() async {
    loading.value = true;
    try {
      var res = await ChatProvider.getUserViewList(searchForm.value);
      userViewList.value = res;
    } finally {
      loading.value = false;
    }
  }

  void tabChange(int index) {
    tabIndex.value = index;
    searchForm.update((val) {
      val!.listType = _typeList[index].type;
    });
    onLoading();
  }

  @override
  void onInit() {
    super.onInit();
    tabList.value = _typeList.map((e) {
      return Tab(
        child: Text(
          e.description,
          style: Get.textTheme.titleSmall?.copyWith(color: Colors.white),
        ),
      );
    }).toList();
    tabController = TabController(length: tabList.length, vsync: this);
    connect();
  }

  void connect() async {
    msgList.clear();
    var url = Commons.getWebsocketUrl();
    if (url == null) {
      return;
    }
    _webSocketManager?.dispose();
    _webSocketManager = WebSocketManager();
    if (_webSocketManager!.isConnect()) {
      await _webSocketManager!.disconnect();
    }
    await _webSocketManager!.connect(url);
    _webSocketManager!.listen(
      (msg) {
        LogUtil.v(msg, tag: "webSocketManager.msg");
        if (ChatConstants.userOnlineMsg == msg) {
          Future.delayed(
            const Duration(seconds: 5),
            () => onLoading(),
          );
          return;
        }
        msgList.add(msg);
        // if (scrollController.hasClients) {
        //   scrollController.animateTo(
        //     scrollController.position.maxScrollExtent,
        //     duration: const Duration(milliseconds: 300),
        //     curve: Curves.easeOut,
        //   );
        // }
      },
    );
    onLoading();
  }

  void sendMsg(String msg) {
    if (_webSocketManager?.isConnect() ?? false) {
      return;
    }
    _webSocketManager!.sendMsg(msg);
  }

  @override
  void onReady() {
    super.onReady();
    //onLoading();
  }

  @override
  void onClose() {
    super.onClose();
    _webSocketManager?.dispose();
  }

  Widget buildProgressMoreIndicator() {
    return Padding(
      padding: const EdgeInsets.all(15.0),
      child: Center(
        child: Obx(
          () => Text(
            loadMoreText.value,
            style: Get.textTheme.bodyMedium,
          ),
        ),
      ),
    );
  }

  void increment() => count.value++;
}
